package com.yuanchu.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanchu.common.utils.PageUtils;
import com.yuanchu.common.utils.Query;
import com.yuanchu.store.dao.YoshopDeliveryRuleDao;
import com.yuanchu.store.dto.DeliveryParamsDto;
import com.yuanchu.store.entity.YoshopDeliveryRuleEntity;
import com.yuanchu.store.service.YoshopDeliveryRuleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("yoshopDeliveryRuleService")
public class YoshopDeliveryRuleServiceImpl extends ServiceImpl<YoshopDeliveryRuleDao, YoshopDeliveryRuleEntity> implements YoshopDeliveryRuleService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<YoshopDeliveryRuleEntity> page = this.page(
                new Query<YoshopDeliveryRuleEntity>().getPage(params),
                new QueryWrapper<YoshopDeliveryRuleEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<DeliveryParamsDto.RulesForm> queryRuleList(Integer deliveryId) {
        List<YoshopDeliveryRuleEntity> deliveryRuleEntities = this.list(new LambdaQueryWrapper<YoshopDeliveryRuleEntity>()
                .eq(YoshopDeliveryRuleEntity::getDeliveryId, deliveryId));
        List<DeliveryParamsDto.RulesForm> collect = deliveryRuleEntities.stream().map(deliveryRule -> {
            DeliveryParamsDto.RulesForm rulesForm = new DeliveryParamsDto.RulesForm();
            BeanUtils.copyProperties(deliveryRule, rulesForm);
            rulesForm.setFirst(deliveryRule.getFirst());
            rulesForm.setRegion(JSON.parseObject(deliveryRule.getRegion(), List.class));
            List<DeliveryParamsDto.RegionTextForm> regionTextFormList = new ArrayList<>();
            List list = JSON.parseObject(deliveryRule.getRegionText(), List.class);
            list.forEach(text -> {
                DeliveryParamsDto.RegionTextForm regionTextForm = JSON.parseObject(text.toString(), DeliveryParamsDto.RegionTextForm.class);
                regionTextFormList.add(regionTextForm);
            });
            rulesForm.setRegionText(regionTextFormList);
            return rulesForm;
        }).collect(Collectors.toList());
        return collect;

    }

}